package com.fahai.web.controller;

import com.fahai.common.ICardType;
import com.fahai.common.PageVo;
import com.fahai.utils.DateUtil;
import com.fahai.utils.json.JsonResult;
import com.fahai.web.entity.CardInfo;
import com.fahai.web.entity.ProductInfo;
import com.fahai.web.entity.SkuInfo;
import com.fahai.web.service.CardInfoService;
import com.fahai.web.vo.CardListVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 套餐控制器
 */

@Controller
@RequestMapping("/card")
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CardInfoController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(CardInfoController.class);

    @Autowired
    CardInfoService service;

    /**
     * 返回界面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String goPage(Model model) {
        // model.addAttribute("selectBar", "场景及产品管理");
        model.addAttribute("selectTab", "tab_auth_1");
        return "card_info";
    }

    /**
     * 充值产品设定列表
     *
     * @param pageVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public JsonResult cardList(PageVo pageVo, Model model, CardListVo vo) {
        PageVo pageVoData = service.findSceneList(vo, pageVo);
        model.addAttribute("selectBar", "场景及产品管理");
        return ok("获取充值产品设定数据", pageVoData);
    }
    /**
     * 产品下拉查询结果
     *
     * @param pageVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/production", method = RequestMethod.POST)
    public JsonResult production(PageVo pageVo, Model model, ProductInfo vo) {
        PageVo pageVoData = service.findProductions(vo, pageVo);
        model.addAttribute("selectBar", "场景及产品管理");
        return ok("获取充值产品设定数据", pageVoData);
    }

    /**
     * 律师校验
     *
     * @param vo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public JsonResult check(CardListVo vo) {
        return ok("获取充值产品设定数据", service.check(vo));
    }

    /**
     * 根据前台传入的查询条件 ，返回总条数
     *
     * @param pageVo
     * @return 总条数
     */
    @ResponseBody
    @RequestMapping(value = "/count", method = RequestMethod.POST)
    public JsonResult count(PageVo pageVo, CardInfo vo) {
        return ok("获取充值产品设定数据", service.count(vo, pageVo));
    }


    /**
     * 更新卡券
     *
     * @param cardListVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResult update(CardListVo cardListVo) {
        if (cardListVo.getTctype() == 1 || cardListVo.getTctype() == 2) {
            //查找旧数据，存在一个问题，如果垃圾数据类型是1，2但是数据存放在sku表里， 那么后果是查不到数据
            //垃圾数据的定义： 类型1，2应该存在card_info表中， 3，4存在 sku_info表中， 如果步这样存放说明类型错误
            CardInfo cardInfo = service.selectCardInfoById(cardListVo.getTcid());
                if (null == cardInfo) {
                return fail("可能存在垃圾数据，未能在应该存在的表中找到该条记录");
            }
            //将前台传入的数据匹配到旧数据对应的字段上
            cardInfo = matchCardInfo(cardListVo, cardInfo);
            cardInfo.setUpdateTime(DateUtil.getCurrentTimestamp());
            service.update(cardInfo);
            logger.info("----------》更新卡券card_info信息");
        } else {
            SkuInfo skuInfo = service.selectSkuInfoById(cardListVo.getTcid());
            skuInfo = matchSkuInfo(cardListVo, skuInfo);
            skuInfo.setUpdateTime(DateUtil.getCurrentTimestamp());
            service.update(skuInfo);
            logger.info("----------》更新卡券sku_info信息");
        }
        return ok("修改成功");
    }


    /**
     * 新增卡券
     *
     * @param cardListVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResult add(CardListVo cardListVo) {
        String tcSn = cardListVo.getTcSn();
        if (tcSn.equals(ICardType.free_ty)) {
            cardListVo.setTctype(1);
        } else if (tcSn.equals(ICardType.free_zy)) {
            cardListVo.setTctype(2);
        } else if (tcSn.equals(ICardType.sku_ty)) {
            cardListVo.setTctype(3);
        } else if (tcSn.equals(ICardType.sku_zy)) {
            cardListVo.setTctype(4);
        } else {

        }

        if (cardListVo.getTctype() == 1 || cardListVo.getTctype() == 2) {
            CardInfo cardInfo = new CardInfo();
            cardInfo = matchCardInfo(cardListVo, cardInfo);
            cardInfo.setTcisopen(0);//0:未上线1:已上线 （即上架下架）
            cardInfo.setProid(cardInfo.getProid());//从前台下拉选择的值
            cardInfo.setTcstats(1);//  0:不可用1:可用 不是上架下架
            if (cardInfo.getTcnumber() == null) {
                cardInfo.setTcnumber("0");
            }
            cardInfo.setPublishUnum(0);//已使用
            service.add(cardInfo);
        } else {
            SkuInfo skuInfo = new SkuInfo();
            skuInfo = matchSkuInfo(cardListVo, skuInfo);
            skuInfo.setSkuisopen(0);
            skuInfo.setProid(cardListVo.getProid());//从前台下拉选择的值
            service.add(skuInfo);
        }
        return ok("修改成功");
    }

    /**
     * 批量上架
     *
     * @param cardListVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/batchOnSale", method = RequestMethod.POST)
    public JsonResult batchOnSale(CardListVo cardListVo) {
        int type = cardListVo.getTctype();
        if (type == 1 || type == 2) {
            List<CardListVo> cards = analysisVos(cardListVo, 1);
            List<Integer> cardids = genIdList(cards);
            service.batchOnSaleCard(cardids);
        } else {
            List<CardListVo> skus = analysisVos(cardListVo, 2);
            List<Integer> skuids = genIdList(skus);
            service.batchOnSaleSku(skuids);
        }


        return ok("修改成功");
    }

    /**
     * 将前台传入的VOS分解成card_info与sku_info两个表的vos
     *
     * @param cardListVo
     * @param voType
     * @return
     */
    public List<CardListVo> analysisVos(List<CardListVo> cardListVo, int voType) {

        List<CardListVo> cards = new ArrayList<CardListVo>();
        List<CardListVo> skus = new ArrayList<CardListVo>();
        for (CardListVo vo :
                cardListVo) {
            if (vo.getTctype() == 1 || vo.getTctype() == 2) {
                cards.add(vo);
            } else {
                skus.add(vo);
            }
        }
        if (voType == 1) {
            return cards;
        } else {
            return skus;
        }

    }

    /**
     * 将前台传入的VOS分解成card_info与sku_info两个表的vos
     *
     * @param vo
     * @param voType
     * @return
     */
    public List<CardListVo> analysisVos(CardListVo vo, int voType) {

        List<CardListVo> cards = new ArrayList<CardListVo>();
        List<CardListVo> skus = new ArrayList<CardListVo>();

        if (vo.getTctype() == 1 || vo.getTctype() == 2) {
            cards.add(vo);
        } else {
            skus.add(vo);
        }

        if (voType == 1) {
            return cards;
        } else {
            return skus;
        }

    }

    /**
     * 批量下架
     *
     * @param cardListVo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/batchDownSale", method = RequestMethod.POST)
    public JsonResult batchDownSale(CardListVo cardListVo) {

        int type = cardListVo.getTctype();
        if (type == 1 || type == 2) {
            List<CardListVo> cards = analysisVos(cardListVo, 1);
            List<Integer> cardids = genIdList(cards);
            service.batchDownSaleCard(cardids);
        } else {
            List<CardListVo> skus = analysisVos(cardListVo, 2);

            List<Integer> skuids = genIdList(skus);
            service.batchDownSaleSku(skuids);
        }


        return ok("修改成功");
    }


    /**
     * 生成主键数组
     *
     * @param list
     * @return
     */
    public List<Integer> genIdList(List<CardListVo> list) {
        List<Integer> lists = new ArrayList<Integer>();

        for (CardListVo vo : list
                ) {
            lists.add(vo.getTcid());
        }
        return lists;
    }


    /**
     * 装配sku_info
     *
     * @param cardListVo
     * @param skuInfo
     * @return
     */
    public SkuInfo matchSkuInfo(CardListVo cardListVo, SkuInfo skuInfo) {

        skuInfo.setSkudeprice(cardListVo.getCallPrice());//定价--》实付金额

        if (cardListVo.getTctype() == 3) {
            skuInfo.setSkutoprice(cardListVo.getFreeTime());
        } else {
            skuInfo.setSkutime(cardListVo.getFreeTime());//面值
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        skuInfo.setSkuType(cardListVo.getTctype());
        skuInfo.setSkuname(cardListVo.getTcName());
        skuInfo.setSkusn(cardListVo.getTcSn() + "-" + cardListVo.getBak());
        try {
            if (cardListVo.getTcStarTime().length() > 10) {
                skuInfo.setSkuStarTime(sf.parse(cardListVo.getTcStarTime().substring(0, 10) + " 00:00:00"));
            } else {
                skuInfo.setSkuStarTime(sf.parse(cardListVo.getTcStarTime() + " 00:00:00"));

            }

            if (cardListVo.getTcEndTime().length() > 10) {
                skuInfo.setSkuEndTime(sf.parse(cardListVo.getTcEndTime().substring(0, 10) + " 23:59:59"));
            } else {
                skuInfo.setSkuEndTime(sf.parse(cardListVo.getTcEndTime() + " 23:59:59"));
            }

        } catch (java.text.ParseException e) {
            e.printStackTrace();
            //TODO 异常未处理
        }


        String tcpublish = cardListVo.getTcPublish();
        if (tcpublish.equals("0")) {
            tcpublish = "法海赋能网络科技有限公司";
            skuInfo.setSkuPublish(tcpublish);
        } else {
            skuInfo.setZdlscode(cardListVo.getZdlscode());//存放律师ID
            skuInfo.setSkuPublish(cardListVo.getLawyername());
        }
        skuInfo.setPublishNum(cardListVo.getPublishNum());//发行数量
        if (cardListVo.getPublishUnum() == null) {
            skuInfo.setPublishUnum(0);//使用数量
        } else {
            skuInfo.setPublishUnum(cardListVo.getPublishUnum());//使用数量
        }
        skuInfo.setSkuisopen(cardListVo.getTcisopen());//是否上线 0否 1是
        skuInfo.setSkucomment(cardListVo.getTcRemark());//备注

        if (skuInfo.getSkustates() == null) {
            skuInfo.setSkustates(1);
        }
        if (skuInfo.getSkuisopen() == null) {
            skuInfo.setSkuisopen(0);
        }
        return skuInfo;
    }

    /**
     * 装配cardInfo
     *
     * @param cardListVo 前台数据
     * @param cardInfo   旧数据
     * @return
     */
    public CardInfo matchCardInfo(CardListVo cardListVo, CardInfo cardInfo) {
        if (null == cardInfo) {
            return null;//不可能存在这种情况，但是有垃圾数据的时候会出现
        }
        cardInfo.setTcSn(cardListVo.getTcSn() + "-" + cardListVo.getBak());
        cardInfo.setTctype(cardListVo.getTctype());
        cardInfo.setTcName(cardListVo.getTcName());
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (cardListVo.getTcStarTime().length() <= 10) {
            cardListVo.setTcStarTime(cardListVo.getTcStarTime() + " 00:00:00");
        }
        Timestamp ds = DateUtil.StringToTimeStamp(cardListVo.getTcStarTime(), "yyyy-MM-dd HH:mm:ss");
        Timestamp de = DateUtil.StringToTimeStamp(cardListVo.getTcEndTime() + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
        cardInfo.setTcStarTime(ds);
        cardInfo.setTcEndTime(de);
        cardInfo.setFreeTime(cardListVo.getFreeTime());//显示价格--次数
        cardInfo.setCallPrice(cardListVo.getCallPrice());//定价--》实付金额
        String tcpublish = cardListVo.getTcPublish();
        if (tcpublish.equals("0")) {
            cardInfo.setTcPublish("法海赋能网络科技有限公司");
        } else {
            cardInfo.setTcPublish(cardListVo.getLawyername());//发行方 --》定向律师
        }
        cardInfo.setZdlscode(cardListVo.getZdlscode());//律师ID
        cardInfo.setPublishNum(cardListVo.getPublishNum());//发行数量
        cardInfo.setPublishUnum(cardListVo.getPublishUnum());//使用数量
//        try {
//            cardInfo.setTcRemark(URLEncoder.encode(cardListVo.getTcRemark(), "utf-8"));//备注
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        cardInfo.setTcRemark(cardListVo.getTcRemark());
        cardInfo.setTcTag(cardListVo.getTcTag());
        cardInfo.setProid(cardListVo.getProid());//2017-07-04 17:49:33增加 产品ID
        if (cardInfo.getPublishUnum() == null) {
            cardInfo.setPublishUnum(0);
        }
        return cardInfo;
    }


}
